import 'package:dio/dio.dart';

import 'base_result.dart';

///@author aidenquan
/// Created by junlintianxia on 1/14/21.

class BaseRepository {
  static const int NETWORK_ERROR = -10000;
  late Dio _dio;

  BaseRepository() {
    _dio = _createDefaultDio();
  }

  ///创建默认dio网络请求对象
  Dio _createDefaultDio() {
    final options = BaseOptions(
      connectTimeout: const Duration(milliseconds: 30 * 1000),
      receiveTimeout: const Duration(milliseconds: 30 * 1000),
    );
    final dio = Dio(options);
    return dio;
  }

  void setDio(Dio dio) {
    _dio = dio;
  }

  ///通用get请求
  Future<dynamic> get(String path,
      {Map<String, String>? headers, Map<String, dynamic>? params}) async {
    try {
      if (headers?.isNotEmpty == true) {
        ///显示指定Map的限定类型 动态添加headers
        _dio.options.headers.addAll(Map<String, String>.from(headers!));
      }
      Response response = await _dio.get(path, queryParameters: params);
      return BaseResult(
          data: response.data,
          code: response.statusCode,
          message: response.statusMessage);
    } catch (e) {
      print('网络请求异常信息：$e');
      return BaseResult(message: e.toString(), code: NETWORK_ERROR);
    }
  }

  /// 通用post请求
  Future<dynamic> post(String path,
      {Map<String, String>? headers, Map<String, dynamic>? params}) async {
    try {
      if (headers?.isNotEmpty == true) {
        ///显示指定Map的限定类型 动态添加headers
        _dio.options.headers.addAll(Map<String, String>.from(headers!));
      }
      Response response = await _dio.post(path, data: params);
      return BaseResult(
          data: response.data,
          code: response.statusCode,
          message: response.statusMessage);
    } catch (e) {
      print('网络请求异常信息：$e');
      return BaseResult(message: e.toString(), code: 500);
    }
  }
}
